package cinema.Controller;

import cinema.Dao.MovieDAO;
import cinema.Entity.Movie;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings("serial")
@Named
@ViewScoped
public class MovieController implements Serializable {

    @Inject
    private MovieDAO movieDAO;

    private String title;
    private int length;
    private String description;
    private Movie movie;

    private List<Boolean> canEdit;

    private List<Movie> movies;

    @PostConstruct
    public void init() {
        movies = movieDAO.findAll();
        canEdit = new ArrayList<Boolean>();
        for (int i = 0; i < movies.size(); ++i) canEdit.add(false);
    }

    public void addMovie() {
        Movie movie = new Movie(title, length, description);
        movies.add(movie);
        canEdit.add(false);
        movieDAO.save(movie);
    }

    public void deleteMovie() {
        try {
            movieDAO.delete(movie);
            canEdit.remove(movies.indexOf(movie));
            movies.remove(movie);
        } catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage("movieTable",
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, "cannot delete movie if showing is registered for it", "cannot delete movie if showing is registered for it"));
        }
    }

    public void editMovie() {
        canEdit.set(movies.indexOf(movie), true);
    }

    public void saveMovie() {
        canEdit.set(movies.indexOf(movie), false);
        movieDAO.update(movie);
    }

    public List<Movie> getMovies() {
        return movies;
    }

    public void setMovies(List<Movie> movies) {
        this.movies = movies;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Movie getMovie() {
        return movie;
    }

    public void setMovie(Movie movie) {
        this.movie = movie;
    }

    public List<Boolean> getCanEdit() {
        return canEdit;
    }

    public void setCanEdit(List<Boolean> canEdit) {
        this.canEdit = canEdit;
    }
}
